package com.example.servicegateway.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Date;
import java.util.Map;

@Slf4j
public class TokenUtils {

    private static final String CLAIM_KEY_UID = "uid";
    private static final String CLAIM_KEY_EXP = "exp";
    private static final String CLAIM_KEY_VER = "ver";

    private static String secret = "secret";
    private static String ver = "1.0";

    private Long expiration = 1000 * 60 * 60L;

    /**
     * 生成token
     * @param userId
     * @return
     */
    public String createToken(Integer userId){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //毫秒数
            Long exp = (Instant.now().getEpochSecond() + 60 * expiration) * 1000;
            log.info("exp: [{}]", exp);
            return JWT.create()
                    .withExpiresAt(new Date(exp))
                    .withClaim(CLAIM_KEY_UID, userId)
                    .withClaim(CLAIM_KEY_VER, ver)
                    .sign(algorithm);
        } catch (JWTCreationException e){
            //Invalid Signing configuration / Couldn't convert Claims.
            log.error("createToken JWTCreationException ", e);
        } catch (Exception e){
            log.error("token Exception ", e);
        }
        return null;
    }

    public static Boolean validateToken(String token) {
        Integer uid = getUidFromToken(token);
        String ver = getVerFromToken(token);
        if (uid == null || uid < 1 || !StringUtils.equals(ver, TokenUtils.ver)) {
            throw new RuntimeException("TOKEN 无效");
        }

        Integer exp = getExpFromToken(token);
        if (exp == null || exp <= Instant.now().getEpochSecond()) {
            throw new RuntimeException("TOKEN 超时");
        }
        return true;
    }

    public static Integer getExpFromToken(String token) {
        Integer exp;
        try {
            Map<String, Claim> claims = getClaimsFromToken(token);
            exp = claims.get(CLAIM_KEY_EXP).asInt();
        } catch (Exception e) {
            exp = 0;
        }
        return exp;
    }

    public static Integer getUidFromToken(String token) {
        Integer uid;
        try {
            Map<String, Claim> claims = getClaimsFromToken(token);
            uid = claims.get(CLAIM_KEY_UID).asInt();
        } catch (Exception e) {
            uid = null;
        }
        return uid;
    }

    public static String getVerFromToken(String token) {
        String ver;
        try {
            Map<String, Claim> claims = getClaimsFromToken(token);
            ver = claims.get(CLAIM_KEY_VER).asString();
        } catch (Exception e) {
            ver = null;
        }
        return ver;
    }

    private static Map<String, Claim> getClaimsFromToken(String token) {
        Map<String, Claim> claims;
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            claims = jwt.getClaims();
        } catch (Exception e) {
            log.error("",e);
            claims = null;
        }
        return claims;
    }
}
